package com.app.android.coliy.dialog;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Rect;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.StyleRes;

import com.app.android.coliy.R;
import com.app.android.coliy.interface_.CommCallBack;
import com.app.android.coliy.util.AnimUtil;
import com.app.android.coliy.util.StatusBarUtil_Dialog;

/**
 * Created by Administrator on 2018/8/29.
 */

public class TextInput_Dialog extends Dialog implements View.OnClickListener {
    public TextInput_Dialog(@NonNull Context context) {
        super(context, R.style.myDialog);
    }

    public TextInput_Dialog(@NonNull Context context, @StyleRes int themeResId) {
        super(context, themeResId);
    }

    protected TextInput_Dialog(@NonNull Context context, boolean cancelable, @Nullable OnCancelListener cancelListener) {
        super(context, cancelable, cancelListener);
    }

    LinearLayout ll_content;
    View view_bg;
    EditText et_input;
    TextView iv_ok;

    CommCallBack callBack;
    String text;
    View mRootView;

    public void setData(String text) {
        this.text = text;
    }

    //设置输入回调
    public void setIntputCallBack(CommCallBack callBack) {
        this.callBack = callBack;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_textinput);
        initView();
        StatusBarUtil_Dialog.setImmersiveStatusBar(this, false);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

        showInputManager(et_input);
    }

    /**
     *
     * @param editText
     */
    private void showInputManager(EditText editText) {
        editText.setFocusable(true);
        editText.setFocusableInTouchMode(true);
        editText.requestFocus();

        /** 目前测试来看，还是挺准的
         * 原理：OnGlobalLayoutListener 每次布局变化时都会调用
         * 界面view 显示消失都会调用，软键盘显示与消失时都调用
         * */
        mRootView.getViewTreeObserver().addOnGlobalLayoutListener(mLayoutChangeListener);
        InputMethodManager inputManager =
                (InputMethodManager)getContext(). getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);

    }

    ViewTreeObserver.OnGlobalLayoutListener mLayoutChangeListener = new ViewTreeObserver
            .OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            //判断窗口可见区域大小
            Rect r = new Rect();
            // getWindowVisibleDisplayFrame()会返回窗口的可见区域高度
            getWindow().getDecorView().getWindowVisibleDisplayFrame(r);
            //如果屏幕高度和Window可见区域高度差值大于整个屏幕高度的1/3，则表示软键盘显示中，否则软键盘为隐藏状态。
            int heightDifference = getScreenHight() - (r.bottom);
            boolean isKeyboardShowing = heightDifference > getScreenHight() / 3;
            if (isKeyboardShowing) {
                // bottomView 需要跟随软键盘移动的布局
                // setDuration(0) 默认300, 设置 0 ，表示动画执行时间为0，没有过程，只有动画结果了
                ll_content.animate().translationY(-heightDifference).setDuration(0).start();
            } else {
                ll_content.animate().translationY(0).start();
            }
        }
    };

    /**
     * 获取屏幕的高度
     * @return
     */
    public int getScreenHight(){
        WindowManager wm = (WindowManager) getContext()
                .getSystemService(Context.WINDOW_SERVICE);

        int height = wm.getDefaultDisplay().getHeight();
        return height;
    }





    private void initView() {
        mRootView = findViewById(R.id.mRootView);
        ll_content = (LinearLayout) findViewById(R.id.ll_content);
        view_bg = findViewById(R.id.view_bg);
        view_bg.setOnClickListener(this);
        ll_content.setOnClickListener(this);
        AnimUtil.fadeIn(view_bg);
        AnimUtil.fadeIn(ll_content);

        et_input = findViewById(R.id.et_input);
        iv_ok = findViewById(R.id.iv_ok);
        iv_ok.setOnClickListener(this);

        et_input.setText(text);
        if (!TextUtils.isEmpty(text)) {
            et_input.setSelection(text.length());
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.view_bg:
                dismissWithAnim();
                break;
            case R.id.ll_content:
                //不处理，只消耗点击事件
                break;
            case R.id.iv_ok:
                String text = et_input.getText().toString();
                if (callBack != null) {
                    callBack.onResult(text);
                }
                break;
        }
    }

    public void dismissWithAnim() {
        if (view_bg.getAnimation() != null) return;
        AnimUtil.fadeOut(ll_content, null);
        AnimUtil.fadeOut(view_bg, new CommCallBack() {
            @Override
            public void onResult(Object obj) {
                dismiss();
            }
        });
    }

    @Override
    public void onBackPressed() {
        dismissWithAnim();
    }
}
